# -*- coding: utf8 -*-

from subprocess import Popen, PIPE
from archive import BaseAdapter, which
import os

class P7ZipArchive(BaseAdapter):

    bin = which("7z")

    def get_files( self ):
        names = []

        p = Popen([
            self.bin,
            "l",
            "-p",
            "-slt",
            "-bd",
            self.file_name
        ], stdout=PIPE)

        while True:

            lines = p.stdout.readlines()

            count = len(lines)
            for i in range(len(lines)):
                l = lines[i].strip()
                if l.lower().startswith("path = "):
                    if i < count-1 and lines[i+1].lower().startswith("folder = -"):
                        names.append( l.replace("Path = ", "") )

            if p.poll() is not None and count == 0:
                break

        return names
    
    def extract_files( self, into_dir):

        dev_null = open(os.devnull, "w")
        p = Popen([
            self.bin,
            "x",
            "-p",
            "-bd",
            '-o%s' % into_dir,
            self.file_name
        ], stdout=dev_null, stderr=dev_null)
        ret = p.wait()
        dev_null.close()

        return ret == 0

    def remove_file( self, name ):
        dev_null = open(os.devnull, "w")
        p = Popen([
            self.bin,
            "d",
            "-p",
            "-bd",
            self.file_name,
            name
        ], stdout=dev_null, stderr=dev_null)
        ret = p.wait()
        dev_null.close()

        return ret == 0
